<?php

namespace App\Http\Controllers\Member;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use App\Rules\ExistsInArray;
use App\CompanyCustomer;
use App\Http\Controllers\Constants;
use Illuminate\Support\Facades\Log;

class CompanyCustomerController extends Controller
{
    private $statusMap = array (
        1 => '禁用',
        2 => '启用'
    );
    private $comAttrTypeMap = array (
        1 => '工厂端',
        2 => '销售端'
    );

    private $statusArray = array(1, 2);

    public function createIndex(Request $request) {
        $dataJson = json_decode(file_get_contents("php://input"), true);
        $res = $this->ownValidate($dataJson, [
            'com_name'=>'required|unique:company_customers',
            'com_link_man'=>'required',   //
            'mobile_phone'=>'required',
            'com_credit_code'=>'required|unique:company_customers',
            'com_attr_type'=>'required',        //企业属性
            'com_type'=>'required',        //企业类型
            'address'=>'required',
            'province'=>'required',
            'city'=>'required',
            'com_login_name'=>'required'
        ]);
        if (!$res['status']) {
            $this->returnData($res['status'], $res['msg']);
        }

        $password = empty($dataJson['pwd']) ? md5('000000') : $dataJson['pwd'];
        $comCode = 111;             //企业代码，需要后台按照一定规则生成
        $companyCustomer = array(
            'com_name' => trim($dataJson['com_name']),              //公司名称
            'com_credit_code' => trim($dataJson['com_credit_code']),//统一信用代码
            'com_link_man' => trim($dataJson['com_link_man']),                //联系人
            'mobile_phone' => trim($dataJson['mobile_phone']),      //联系电话
            'pwd' => Hash::make($password),                        //登陆密码
            'com_attr_type' => $dataJson['com_attr_type'],          //企业属性：工厂端/销售端
            'com_code' => $comCode,                    //企业代码，后端生成
            'com_login_name' => $dataJson['com_login_name'],          //企业登陆名称使用手机号
            'city' => $dataJson['city'],          //企业登陆名称使用手机号
            'province' => $dataJson['province'],          //企业登陆名称使用手机号
            'address' => $dataJson['address'],          //企业登陆名称使用手机号
            'com_type' => $dataJson['com_type'],          //企业登陆名称使用手机号
            'note' => $dataJson['note']          //企业登陆名称使用手机号
        );
        $companyCustomer = CompanyCustomer::create($companyCustomer);

        if (!empty($companyCustomer)) {
            $retData = array(
                'id' => $companyCustomer->id
            );

            $this->returnData(true, '用户添加成功', $retData);
        } else {
            $this->returnData(false, '用户添加失败', null);
        }
    }

    public function getIndex(Request $request) {
        $data = $request->all();
        $currentPage = !empty($data['current_page']) ? $data['current_page'] : 1;
        $perPage = !empty($data['per_page']) ? $data['per_page'] : 10;
        $offset = ($currentPage - 1) * $perPage;
        $limit = $perPage;

        $where = array();
        if (!empty($data['com_name'])) {
            $where[] = ['customer.com_name', 'like', '%' . $data['com_name'] . '%'];
        }
        if (!empty($data['com_link_man'])) {
            $where[] = ['customer.com_link_man', 'like', '%' . $data['com_link_man'] . '%'];
        }
        if (!empty($data['mobile_phone'])) {
            $where[] = ['customer.mobile_phone', 'like', '%' . $data['mobile_phone'] . '%'];
        }
        if (!empty($data['member_type'])) {
            $where[] = ['customer.member_type', $data['member_type']];
        }
        if (!empty($data['customer.status'])) {
            $where[] = ['customer.status', $data['status']];
        }
        if (!empty($data['create_time_left'])) {
            $where[] = ['customer.created_at', '>=', date('Y-m-d', strtotime($data['create_time_left']))];
        }
        if (!empty($data['create_time_right'])) {
            $where[] = ['customer.created_at', '<=', date('Y-m-d', strtotime($data['create_time_right'] . " +1 day"))];
        }
        if (!empty($data['enddate_at_left'])) {
            $where[] = ['customer.enddate_at', '>=', date('Y-m-d', strtotime($data['enddate_at_left']))];
        }
        if (!empty($data['enddate_at_right'])) {
            $where[] = ['customer.enddate_at', '<=', date('Y-m-d', strtotime($data['enddate_at_right'] . " +1 day"))];
        }

        $companyCustomerList = CompanyCustomer::getCompanyCustomer($where, $limit, $offset);
        foreach ($companyCustomerList as &$companyCustomer) {
            $companyCustomer['status_name'] = $this->statusMap[$companyCustomer['status']];
            $companyCustomer['com_attr_type_name'] = $this->comAttrTypeMap[$companyCustomer['com_attr_type']];
        }

        $total = CompanyCustomer::getTotal($where);

        $data = array(
            'total' => $total,
            'data' => $companyCustomerList
        );

        $this->returnData(true, 'success', $data);
    }

    public function editIndex() {
        $dataJson = json_decode(file_get_contents("php://input"), true);

        $res = $this->ownValidate($dataJson, [
            'company_customer_id'=>'required|integer',   //
            'com_name'=>'required|unique:company_customers,com_name,' . $dataJson['company_customer_id'],
            'com_link_man'=>'required',   //
            'mobile_phone'=>'required',
            'com_credit_code'=>'required|unique:company_customers,com_credit_code,' . $dataJson['company_customer_id'],
            'com_attr_type'=>'required|integer',        //企业属性
            'com_type'=>'required|integer',        //企业类型
//            'pwd'=>'required',
            'address'=>'required',
            'province'=>'required',
            'city'=>'required',
            'enddate_at'=>'required',
//            'pwd_reset'=>'required',
            'com_login_name'=>'required'
        ]);
        if (!$res['status']) {
            $this->returnData($res['status'], $res['msg']);
        }

        $companyCustomer = CompanyCustomer::find($dataJson['company_customer_id']);
        $companyCustomer->com_name = $dataJson['com_name'];
        $companyCustomer->com_credit_code = $dataJson['com_credit_code'];
        $companyCustomer->com_link_man = $dataJson['com_link_man'];
        $companyCustomer->mobile_phone = $dataJson['mobile_phone'];
        $companyCustomer->com_attr_type = $dataJson['com_attr_type'];
        $companyCustomer->com_login_name = $dataJson['com_login_name'];
        $companyCustomer->city = $dataJson['city'];
        $companyCustomer->province = $dataJson['province'];
        $companyCustomer->address = $dataJson['address'];
        $companyCustomer->com_type = $dataJson['com_type'];
        $companyCustomer->enddate_at = $dataJson['enddate_at'];
        if (!empty($dataJson['pwd_reset'])) {
            $companyCustomer->pwd = Hash::make($dataJson['pwd']);
        }
        $res = $companyCustomer->save();
        if ($res) {
            $this->returnData(true, '编辑成功');
        }

        $this->returnData(false, '编辑失败');
    }

    public function changeStatus() {
        $dataJson = json_decode(file_get_contents("php://input"), true);
        $res = $this->ownValidate($dataJson, [
            'status' => ['required', new ExistsInArray($this->statusArray)],
            'company_customer_id'=>'required|integer'
        ]);
        if (!$res['status']) {
            $this->returnData($res['status'], $res['msg']);
        }

        $companyCustomer = CompanyCustomer::find($dataJson['company_customer_id']);
        if (empty($companyCustomer)) {
            $this->returnData(false, '无此会员');
        }

        $companyCustomer->status = $dataJson['status'];
        if (($dataJson['status'] == 2) && (empty($companyCustomer['db_name']))) {
            $dbName = Constants::DB_NAME . '_' . $companyCustomer['id'];

            $param = array(
                'db_name' => $dbName,
                'company_customer' => $companyCustomer
            );
            $res = $this->createDatabase($param);
            if (!$res->status) {
                $this->returnData(false, '初始化用户数据失败');
            }

            $companyCustomer->db_name = $dbName;
        }

        $res = $companyCustomer->save();
        if ($res) {
            $this->returnData(true, $this->statusMap[$dataJson['status']] . '成功');
        }

        $this->returnData(false, $this->statusMap[$dataJson['status']] . '失败');
    }

    private function createDatabase($param) {
        $customerHost = env('CUSTOMER_HOST', 'http://localhost:8092/');
        $customerApi = $customerHost . 'Api/CompanyCustomer/createDatabase';

        $ret = $this->normalCurl($customerApi, $param, true);

        return json_decode($ret);
    }
}
